package com.cskaoyan.udp.edition3.anotherperson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/*
        发送线程执行的发送任务
 */
public class SenderTask implements Runnable {

    DatagramSocket datagramSocket;

    // 发送数据的目标主机ip
    InetAddress targetIp;

    int port;

    public SenderTask(DatagramSocket datagramSocket, InetAddress targetIp, int port) {
        this.datagramSocket = datagramSocket;
        this.targetIp = targetIp;
        this.port = port;
    }

    @Override
    public void run() {
        // 准备读取键盘录入字符串的缓冲字符输入流
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String line;
        try {
            while ((line = br.readLine()) != null) {
                // 将读取的数据封装到数据报包中
                byte[] bytes = line.getBytes();
                DatagramPacket sendPacket
                        = new DatagramPacket(bytes, 0, bytes.length, targetIp, port);

                // 将数据报包发送出去
                datagramSocket.send(sendPacket);

                if ("886".equals(line)) {
                    synchronized (datagramSocket) {
                        AnotherPerson.senderOffline = true;
                        break;
                    }

                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
